package com.weipeep.sys.shiro;

import com.google.common.collect.Sets;
import com.weipeep.common.utils.ShiroUtils;
import com.weipeep.common.utils.SpringContextHolder;
import com.weipeep.sys.dao.UserDao;
import com.weipeep.sys.dao.WebUserDao;
import com.weipeep.sys.domain.UserBase;
import com.weipeep.sys.domain.UserDO;
import com.weipeep.sys.domain.WebUserDO;
import com.weipeep.sys.service.MenuService;
import io.swagger.models.auth.In;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.*;

/**
 * <pre>
 * </pre>
 * 
 * <small> 2018年3月23日 | wangyun</small>
 */
public class UserRealm extends AuthorizingRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
        Long userId = ShiroUtils.getUserId();
        Integer memberType = ShiroUtils.getUser().getMemberType();
        Integer userType = ShiroUtils.getUser().getUserType();
        MenuService menuService = SpringContextHolder.getBean(MenuService.class);
        Set<String> perms = menuService.listPerms(userId);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        if (userType==1){
            info.setRoles(Sets.newHashSet("member"));
            if (memberType==1){
                perms.add("buyer");
            }
            if (memberType==2){
                perms.add("seller");
            }
            if (memberType==3){
                perms.add("buyer");
                perms.add("seller");
            }
        }else if (userType==2){
            info.setRoles(Sets.newHashSet("admin"));
            perms.add("admin");
        }

        info.setStringPermissions(perms);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String userAccountRole = (String) token.getPrincipal();
        String[] userAccountStr = userAccountRole.split("#&#");
        String userAccount = userAccountStr[0];
        Integer roleType = Integer.valueOf(userAccountStr[1]);
        Map<String, Object> map = new HashMap<>(16);
        if (roleType==1){//会员
            map.put("user_account", userAccount);
        }else if (roleType==2){
            map.put("username", userAccount);
        }
        String password = new String((char[]) token.getCredentials());
        WebUserDao webUserMapper = SpringContextHolder.getBean(WebUserDao.class);
        UserDao userMapper = SpringContextHolder.getBean(UserDao.class);
        // 查询用户信息
        WebUserDO webUserDO = null;;
        UserDO userDO = null;
        if (roleType==1){//会员
            List<WebUserDO> webUserDOs = webUserMapper.selectByMap(map);
            if (webUserDOs !=null && webUserDOs.size()>0){
                webUserDO =webUserDOs.get(0);
            }
            // 账号不存在
            if (webUserDO == null) {
                throw new UnknownAccountException("账号或密码不正确");
            }
            // 密码错误
            if (!password.equals(webUserDO.getPassword())) {
                throw new IncorrectCredentialsException("账号或密码不正确");
            }

            // 账号锁定
            if (webUserDO.getStatus() == 0) {
                throw new LockedAccountException("账号已被锁定,请联系管理员");
            }
            // 账号锁定
            if (webUserDO.getStatus() == 2) {
                throw new LockedAccountException("账号缴费已过期,请联系管理员");
            }
        }
        if (roleType==2){//管理员
            List<UserDO> userDOS = userMapper.selectByMap(map);
            if (userDOS !=null && userDOS.size()>0){
                userDO =userDOS.get(0);
            }
            // 账号不存在
            if (userDO == null) {
                throw new UnknownAccountException("账号或密码不正确");
            }
            // 密码错误
            if (!password.equals(userDO.getPassword())) {
                throw new IncorrectCredentialsException("账号或密码不正确");
            }
        }
        UserBase userBase = null;
        if (webUserDO!=null){
            userBase = new UserBase();
            userBase.setId(webUserDO.getId());
            userBase.setMemberType(webUserDO.getMemberType());
            userBase.setUserAccount(webUserDO.getUserAccount());
            userBase.setUserName(webUserDO.getUserName());
            userBase.setUserType(1);
            userBase.setMemberLevel(webUserDO.getMemberLevel());
        }
        if (userDO!=null){
            userBase = new UserBase();
            userBase.setId(userDO.getId());
            userBase.setUserAccount(userDO.getUsername());
            userBase.setUserName(userDO.getName());
            userBase.setUserType(2);
            userBase.setMemberLevel(0);
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userBase, password, getName());
        return info;
    }

}
